package cn.jcet;

import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * @author 鲜磊
 * @Date 2021/1/7 23:31
 */
public class DistributeServer {

    private ZooKeeper zkServer;

    public static void main(String[] args) {
        DistributeServer server = new DistributeServer();
        // 连接
        server.connect();

        // 创建节点
        server.register(args[0]);
        // 等待
        server.business();
    }

    private void business() {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void register(String hostname) {
        // 创建节点,都是临时节点并且都是带序号，因为路径相同
        try {
            String path = zkServer.create("/servers/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            // 主机名称家服务名称
            System.out.println(hostname+" is online" + path);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void connect() {
        try {
          zkServer =   new ZooKeeper(GetConnection.STRINGCONNECT, GetConnection.SESSIONTIME, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
